package com.hejing.Map接口及其实现类的使用;

import org.junit.Test;

import java.util.Comparator;
import java.util.Set;
import java.util.TreeMap;

/**
 * ClassName: TreeMapTest
 * Package: com.hejing.Map接口及其实现类的使用
 * Description:
 *
 * @Author: HeJing
 * @Create: 2023-05-20 18:56
 * @Version: 1.0
 */
public class TreeMapTest {

    /**
     * 自然排序: String
     */
    @Test
    public void test01(){

        TreeMap map = new TreeMap();
        map.put("DD", true);
        map.put("CC", 'c');
        map.put("JJ", "CHINA");
        map.put("MM", 90);
        
        // map.put(123, 123); 此处的key的类型与前面的不一致，报错。

        Set entrySet = map.entrySet();
        for(Object entry: entrySet) {
            System.out.println(entry);
        }
    }

    /**
     * 自然排序: 自定义类(User)
     */
    @Test
    public void test02(){

        TreeMap map = new TreeMap();

        User u1 = new User("Tom", 23);
        User u2 = new User("Luffy", 25);
        User u3 = new User("Jack", 18);
        User u4 = new User("LiHua", 23);
        User u5 = new User("HanMeiMei", 33);

        map.put(u1, 78);
        map.put(u2, 71);
        map.put(u3, 90);
        map.put(u4, 73);
        map.put(u5, 89);

        Set entrySet = map.entrySet();
        for(Object entry: entrySet) {
            System.out.println(entry);
        }
    }

    /**
     * 定制排序:
     */
    @Test
    public void test03(){

        Comparator comparator = new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof User && o2 instanceof User) {
                    User u1 = (User) o1;
                    User u2 = (User) o2;

                    // 制定标准: 姓名从小到大，年龄从大到小
                    int value = u1.getName().compareTo(u2.getName());
                    if(value != 0) return value;  // 从小到大
                    return -(u1.getAge() - u2.getAge());  // 从大到小
                }
                throw new RuntimeException("类型不匹配");
            }
        };
        TreeMap map = new TreeMap(comparator);

        User u1 = new User("Tom", 23);
        User u2 = new User("Tom", 25);
        User u3 = new User("Jack", 18);
        User u4 = new User("LiHua", 23);
        User u5 = new User("HanMeiMei", 33);

        map.put(u1, 78);
        map.put(u2, 71);
        map.put(u3, 90);
        map.put(u4, 73);
        map.put(u5, 89);

        Set entrySet = map.entrySet();
        for(Object entry: entrySet) {
            System.out.println(entry);
        }
    }
}


















